package org.usmile.algorithms.leetcode.middle;

import org.usmile.algorithms.leetcode.ListNode;

/**
 * 82. 删除排序链表中的重复元素 II
 *
 * 给定一个已排序的链表的头 head ， 删除原始链表中所有重复数字的节点，只留下不同的数字 。返回 已排序的链表 。
 *
 * 示例 1：
 * 输入：head = [1,2,3,3,4,4,5]
 * 输出：[1,2,5]
 *
 * 示例 2：
 * 输入：head = [1,1,1,2,3]
 * 输出：[2,3]
 *
 * 提示：
 * 链表中节点数目在范围 [0, 300] 内
 * -100 <= Node.val <= 100
 * 题目数据保证链表已经按升序 排列
 */
public class _0082 {
}

class _0082_Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode prev = dummy;
        ListNode curr = head;
        while (curr != null) {
            if (curr.next != null && curr.val == curr.next.val) {
                do {
                    curr = curr.next;
                } while (curr.next != null && curr.val == curr.next.val);
                prev.next = curr.next;
                curr.next = null;
            } else {
                prev = curr;
            }
            curr = prev.next;
        }
        return dummy.next;
    }
}

class _0082_Solution1 {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        ListNode prev = dummy;
        ListNode curr = head;
        while (curr != null) {
            int currVal = curr.val;
            if (curr.next != null && currVal == curr.next.val) {
                while (curr != null && curr.val == currVal) {
                    curr = curr.next;
                }
                continue;
            }
            prev.next = new ListNode(currVal);
            prev = prev.next;
            curr = curr.next;
        }

        return dummy.next;
    }
}